package com.lhd.charging.order.config;

import com.lhd.charging.order.dao.repository.OrderRepository;
import com.lhd.charging.order.mqtt.MqttConsumer;
import com.lhd.charging.order.service.OrderService;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MqttConfig {

    private String username = "admin";

    private String password = "public";

    private String host = "tcp://localhost:1883";

    private String clientId = "order_service_client";

    private MqttClient mqttClient;

    @Autowired
    private OrderRepository orderRepository;

    @Bean
    public MqttClient mqttClient() throws Exception {
        mqttClient = new MqttClient(host,clientId);

        MqttConnectOptions connOpts = new MqttConnectOptions();
        //用户名
        connOpts.setUserName(username);
        //密码
        connOpts.setPassword(password.toCharArray());
        //自动重连
        connOpts.setAutomaticReconnect(true);
        //版本号设置
        connOpts.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        //清理会话session
        connOpts.setCleanSession(true);
        // 创建mqtt消费者
        MqttConsumer mqttConsumer = new MqttConsumer(mqttClient, orderRepository);
        // 设置消费者
        mqttClient.setCallback(mqttConsumer);

        //基于上面配置号的连接相关的配置,进行连接
        mqttClient.connect(connOpts);

        //返回连接客户端
        System.out.println(mqttClient);
        return mqttClient;
    }

}
